package com.hanxiaozhang.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hanxiaozhang.context.TenantContext;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 〈一句话功能简述〉<br>
 * 〈填充字段〉
 *
 * @author hanxinghua
 * @create 2025/6/18
 * @since 1.0.0
 */
public class FillMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        // 租户ID填充 todo
        String tenantId = TenantContext.getCurrentTenant();
        if (tenantId != null) {
            this.strictInsertFill(metaObject, "tenantId", String.class, tenantId);
        }

        // 严格模式会在字段不存在时跳过填充
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 用户ID可能为null的情况
        Long userId = getCurrentUserId();
        if (userId != null) {
            // 创建人 - 只有为空时才填充
            fillIfAbsent(metaObject, "createBy", userId);
            // 修改人 - 只有为空时才填充
            fillIfAbsent(metaObject, "updateBy", userId);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {

    }


    /**
     * 当字段值为null或空时才填充
     */
    private void fillIfAbsent(MetaObject metaObject, String fieldName, Object value) {
        Object currentValue = getFieldValByName(fieldName, metaObject);
        if (currentValue == null || (currentValue instanceof String && ((String) currentValue).isEmpty())) {
            this.setFieldValByName(fieldName, value, metaObject);
        }
    }

    /**
     * 获取当前用户id
     *
     * @return
     */
    private Long getCurrentUserId() {
        return null;
    }
}
